﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using Ultimus.WFServer;

namespace AkazoNobel.Ultimus.Extension
{
    public static class UltimusVariable
    {
        /// <summary>
        /// 日志记录
        /// </summary>
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// 向变量列表添加变量
        /// </summary>
        /// <param name="variables">列表</param>
        /// <param name="name">变量名</param>
        /// <param name="value">变量值</param>
        /// <returns>添加变量后的列表数量</returns>
        public static int Add(this List<Variable> variables, string name, object value)
        {
            value = value ?? "";

            var variable = new Variable {strVariableName = name};

            if (value.GetType().IsArray)
            {
                variable.objVariableValue = value as object[];
            }
            else
            {
                variable.objVariableValue = new object[1];
                variable.objVariableValue[0] = value;
            }
            variables.Add(variable);

            return variables.Count;
        }
        
        /// <summary>
        /// 获取Task变量
        /// </summary>
        /// <param name="task">task</param>
        /// <param name="name">变量名</param>
        /// <returns></returns>
        public static string GetString(this Task task, string name)
        {
            var strError = "";
            object value = null;

            if (!task.GetVariableValue(name, out value, out strError) || strError != "")
            {
                Logger.Error(strError);
            }

            value = value ?? "";
            if (value.GetType().IsArray)
            {
                var values = value as object[];
                if (values != null) value = values[0];
            }

            return value as string;
        }

        public static string[] GetArray(this Task task, string name)
        {
            var strError = "";
            object value = null;

            if (!task.GetVariableValue(name, out value, out strError) || strError != "")
            {
                Logger.Error(strError);
            }

            value = value ?? new string[0];
            if (!value.GetType().IsArray)
            {
                value = new string[0];
            }

            return value as string[];
        }

    }
}
